//
//  ConnectView.swift
//  xgwjinterconnection
//  设备连接页面
//  Created by WangWeiShuo on 2025/8/27.
//

import SwiftUI

struct DeviceConnectView: View {
    @Environment(\.dismiss) var dismiss
    // 引用Socket管理器
    @ObservedObject private var socketManager = SocketManager.shared
    @State private var isNavigatedToHome = false
    
    // 输入字段
    @State private var host = "192.168.4.199"
    @State private var port = "1995"
    @State private var message = ""
    
    @State private var scannedCode: String?
    @State private var showScanner = false
    
    @StateObject private var viewModel = DeviceConnectVM()
    
    var body: some View {
        NavigationStack{
            ZStack(alignment: .bottom){
                
                VStack{
                    //                WikaNavigationView(showBackIcon: false, title: "设备连接",onBack: {
                    //                    dismiss() }).frame(maxHeight: 65)
                    
                    HStack() {
                        // 自定义导航栏（确保标题和返回按钮在同一行）
                        Spacer().frame(maxWidth: .infinity)
                        Text(NSLocalizedString("connect_device", comment: "设备连接"))
                            .font(.title3)
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                        
//                        Button(action: connect) {
//                            Image(systemName: "qrcode.viewfinder")
//                                .foregroundColor(.white)
//                        }.frame(maxWidth: .infinity,alignment: .trailing)
                        Button{
                            showScanner = true
                        } label: {
                            Image(systemName: "qrcode.viewfinder")
                                .foregroundColor(.white)
                        }.frame(maxWidth: .infinity,alignment: .trailing)
                    }
                    .padding(.top,50)
                    .frame(maxWidth: .infinity, maxHeight: 65)
                    .padding()
                    .background(
                        Image("bg_titlebar")
                            .resizable()
                    )
                    .edgesIgnoringSafeArea(.top)
                    
                    Spacer()
                }
                
                VStack{
                    Text(viewModel.message)
                        .font(.title3)
                        .foregroundColor(.black)
                    
                    Text(NSLocalizedString("connect_tips", comment: "请确保手机Wi-Fi为打开状态"))
                        .padding(.top,1)
                        .foregroundColor(.black)
                }
                .padding()
                .frame(maxWidth: .infinity)
                .background(Color("color_gray_f3f3f3"))
                .cornerRadius(8)
                .padding(.bottom,100)
                .padding(.horizontal)
                
                
                CustomButton(name: NSLocalizedString("connect_text", comment: "连接")) {
                    connect()
//                    viewModel.connect(ssid: "DIRECT-XCMG", passphrase: "123456789")
                }
            }
            .navigationBarBackButtonHidden(true)
            .enableSwipeBackGesture()
            .navigationDestination(isPresented: $isNavigatedToHome) {
                MainView()
            }
            .onChange(of: socketManager.state) { newState in
                if(newState == .connected){
                    isNavigatedToHome = true
                }
            }
        }
        .onChange(of: scannedCode ?? ""){ newValue in
            print("扫描结果 = \(newValue)")
            let (ssid, pwd) = CommonUtils.parseWiFi(from: newValue)
            print("扫描结果 ssid = \(ssid),,,,pwd = \(pwd)")
            viewModel.connect(ssid: ssid!, passphrase: pwd!)
        }
        .onChange(of: viewModel.isConnected){ connected in
            print("连接Wi-Fi = \(connected)")
            if(connected){
                connect()
            }
        }
        .sheet(isPresented: $showScanner) {
                        QRScannerView { result in
                            scannedCode = result
                            showScanner = false   // 自动关闭
                        }
                    }
    }
    
    // 连接状态文本
    private var connectionStateText: String {
        switch socketManager.state {
        case .disconnected:
            return NSLocalizedString("connect_dis", comment: "未连接")
        case .connecting:
            return NSLocalizedString("connecting", comment: "连接中...")
        case .connected:
            return NSLocalizedString("connected", comment: "已连接")
        case .error(let error):
            return "错误: \(error)"
        }
    }
    
    // 连接状态颜色
    private var connectionStateColor: Color {
        switch socketManager.state {
        case .disconnected:
            return .gray
        case .connecting:
            return .orange
        case .connected:
            return .green
        case .error:
            return .red
        }
    }
    
    // 连接到服务器
    private func connect() {
        guard let portNumber = UInt16(port) else {
            socketManager.messages.append("无效的端口号")
            return
        }
        socketManager.connect(host: host, port: portNumber)
    }
    
    // 断开连接
    private func disconnect() {
        socketManager.disconnect()
    }
    
    // 发送消息
    private func sendMessage() {
        socketManager.sendMessage(message)
        message = ""
    }
}

#Preview {
    DeviceConnectView()
}
